package cn.edu.tju.elm.service;

import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.repository.UserRepository;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.exception.DatabaseException;
import cn.edu.tju.elm.exception.ForbiddenException;
import cn.edu.tju.elm.exception.MethodArgumentNotValidException;
import cn.edu.tju.elm.exception.DataNotFoundException;
import cn.edu.tju.elm.model.entity.DeliveryAddress;
import cn.edu.tju.elm.repository.DeliveryAddressRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeliveryAddressService {
    private final DeliveryAddressRepository deliveryAddressRepository;
    private final UserRepository userRepository;
    private final UserService userService;

    public DeliveryAddressService(DeliveryAddressRepository deliveryAddressRepository, UserRepository userRepository, UserService userService) {
        this.deliveryAddressRepository = deliveryAddressRepository;
        this.userRepository = userRepository;
        this.userService = userService;
    }

    /**
     * 新增地址
     * @param deliveryAddress 地址，只需要contactName、contactTel、address
     * @return DeliveryAddress
     */
    public DeliveryAddress addDeliveryAddress(DeliveryAddress deliveryAddress) {
        User nowUser = userService.getUserWithAuthorities();
        LocalDateTime now = LocalDateTime.now();
        DeliveryAddress address = DeliveryAddress.builder()
                .address(deliveryAddress.getAddress())
                .contactName(deliveryAddress.getContactName())
                .contactTel(deliveryAddress.getContactTel())
                .contactSex(deliveryAddress.getContactSex())
                .customer(nowUser)

                .deleted(false)
                .createTime(now)
                .updateTime(now)
                .creator(nowUser.getId())
                .updater(nowUser.getId())

                .build();

        // 性别默认为1（MALE）
        if(deliveryAddress.getContactSex() == null){
            deliveryAddress.setContactSex(1);
        }

        return deliveryAddressRepository.save(address);
    }

    public List<DeliveryAddress> listDeliveryAddress() {
        User nowUser = userService.getUserWithAuthorities();
        List<DeliveryAddress> addresses = deliveryAddressRepository.findAllByCustomer(nowUser);
        return addresses;
    }

    public DeliveryAddress deleteDeliveryAddress(Long id) {
        User nowUser = userService.getUserWithAuthorities();
        DeliveryAddress deliveryAddress = deliveryAddressRepository.findById(id)
                .orElseThrow(()->new MethodArgumentNotValidException("请求参数非法：配送地址不存在"));
        if(!nowUser.equals(deliveryAddress.getCustomer())){
            throw new ForbiddenException("权限不足：仅可删除当前用户的配送地址");
        }
        try {
            deliveryAddressRepository.delete(deliveryAddress);
        } catch (Exception e){
            throw new DatabaseException("数据库操作异常");
        }
        return null;
    }

    public DeliveryAddress updateDeliveryAddress(Long id, DeliveryAddress deliveryAddress) {
        User nowUser = userService.getUserWithAuthorities();
        DeliveryAddress exDeliveryAddress = deliveryAddressRepository.findById(id)
                .orElseThrow(()->new MethodArgumentNotValidException("请求参数非法：配送地址不存在"));
        if(!nowUser.equals(deliveryAddress.getCustomer())){
            throw new ForbiddenException("权限不足：仅可编辑当前用户的配送地址");
        }
        exDeliveryAddress.setAddress(deliveryAddress.getAddress());
        exDeliveryAddress.setContactName(deliveryAddress.getContactName());
        exDeliveryAddress.setContactSex(deliveryAddress.getContactSex());
        exDeliveryAddress.setContactTel(deliveryAddress.getContactTel());

        DeliveryAddress result = new DeliveryAddress();
        try {
            result = deliveryAddressRepository.save(exDeliveryAddress);
        } catch (Exception e){
            throw new DatabaseException("数据库操作异常");
        }
        return result;
    }
}
